#include <ctime>
#include <iostream>
#include "ErrorManager.h"

AgoraCore::IErrorManager*	AgoraCore::ErrorManager::_instance = NULL;

AgoraCore::ErrorManager::ErrorManager()
{
}

AgoraCore::IErrorManager*	AgoraCore::ErrorManager::GetErrorManager()
{
	if (ErrorManager::_instance == NULL)
		ErrorManager::_instance = new ErrorManager();
	return ErrorManager::_instance;
}

AgoraCore::IError*	AgoraCore::ErrorManager::GetError()
{
	if (!this->_errorStack.empty())
	{
		AgoraCore::IError* err = this->_errorStack.top();
		this->_errorStack.pop();
		return err;
	}
	return NULL;
}

void	AgoraCore::ErrorManager::AddError(AgoraCore::IError* error)
{
	this->_errorStack.push(error);
	//if (this->_logActivated)
	//{
	//	std::ostream os(&this->_fb);
	//	time_t	t;
	//	time(&t);
	//	os << ctime(&t) << " : " << error->GetMessage() << std::endl; //il serait bien d'avoir plus d'infos
	//}
}

std::stack<AgoraCore::IError*>	AgoraCore::ErrorManager::GetAllError()
{
	return this->_errorStack;
}

void	AgoraCore::ErrorManager::PurgeError()
{
	while (!this->_errorStack.empty())
	{
		AgoraCore::IError* err = this->_errorStack.top();
		delete err;
		this->_errorStack.pop();
	}
}

bool	AgoraCore::ErrorManager::HasError()
{
	return !this->_errorStack.empty();
}

void	AgoraCore::ErrorManager::SetLogFilePath(const std::string& filePath)
{
	this->_logFilePath = filePath;
	if (this->_fb.is_open())
		this->_fb.close();
	this->_fb.open(filePath.c_str(), std::ios::app);
	if (this->_logActivated = true && !this->_fb.is_open())
		this->_logActivated = false;
}

const std::string&	AgoraCore::ErrorManager::GetLogFilePath()
{
	return this->_logFilePath;
}

void	AgoraCore::ErrorManager::Log(bool activate)
{
	if (activate && !this->_fb.is_open())
		this->_logActivated = false;
	else
		this->_logActivated = activate;
}

bool	AgoraCore::ErrorManager::LogIsActivated()
{
	return this->_logActivated;
}